package com.salary.utils.reader;

import com.salary.model.SalesInfo;
import com.salary.model.SalesRecord;
import com.salary.utils.GlobalDataStore;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SalesDataReader extends DataReader<List<SalesRecord>> {
    private static final Logger logger = LoggerFactory.getLogger(SalesDataReader.class);
    @Override
    public List<SalesRecord> readData(String filePath) {
        List<SalesRecord> records = new ArrayList<>();
        // 创建SalaryInfo对象，用于记录销售总量
        SalesInfo salesInfo = new SalesInfo();
        double totalSalesQuantity = 0.0;

        try (FileInputStream fis = new FileInputStream(filePath);
             Workbook workbook = WorkbookFactory.create(fis)) {

            // 查找名为"数据源"的工作表
            Sheet sheet = workbook.getSheet("数据源");
            if (sheet == null) {
                logger.error("未找到名为'数据源'的工作表");
                return records;
            }

            // 获取标题行，确定各字段的列索引
            Map<String, Integer> columnMap = new HashMap<>();
            Row headerRow = sheet.getRow(0);
            if (headerRow != null) {
                for (int i = 0; i < headerRow.getLastCellNum(); i++) {
                    Cell cell = headerRow.getCell(i);
                    if (cell != null) {
                        String columnName = cell.getStringCellValue().trim();
                        columnMap.put(columnName, i);
                    }
                }
            }

            // 确保所需字段存在
            if (!columnMap.containsKey("业务员") || !columnMap.containsKey("数量") ||
                    !columnMap.containsKey("吨纸毛利") || !columnMap.containsKey("客户编码") ||
                    !columnMap.containsKey("存货名称") || !columnMap.containsKey("仓库")) {
                logger.error("Excel中缺少必要的字段");
                // 记录所有找到的字段，以便调试
                StringBuilder foundColumns = new StringBuilder("找到的列：");
                for (String column : columnMap.keySet()) {
                    foundColumns.append(column).append(", ");
                }
                logger.error(foundColumns.toString());
                return records;
            }

            // 读取数据行
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;

                // 读取各字段值
                String salesperson = getCellValueAsString(row.getCell(columnMap.get("业务员")));

                // 如果业务员为空，跳过该行
                if (salesperson.isEmpty()) continue;

                double quantity = 0;
                double paperProfit = 0;
                String customerCode = "";
                String stockName = "";
                String warehouse = "";
                String salesperson2 = ""; // 添加业务员2字段

                try {
                    Cell quantityCell = row.getCell(columnMap.get("数量"));
                    if (quantityCell != null) {
                        quantity = quantityCell.getNumericCellValue();

                        // 累计销售总量，排除"东莞诚昌"业务员的数量
                        if (!"东莞诚昌".equals(salesperson.trim())) {
                            totalSalesQuantity += quantity;
                            logger.info("业务员[" + salesperson + "]销售量: " + quantity + "吨，累计销售总量: " + totalSalesQuantity + "吨");
                        } else {
                            logger.info("业务员[东莞诚昌]销售量: " + quantity + "吨，不计入销售总量");
                        }
                    }

                    Cell paperProfitCell = row.getCell(columnMap.get("吨纸毛利"));
                    if (paperProfitCell != null) {
                        paperProfit = paperProfitCell.getNumericCellValue();
                    }

                    customerCode = getCellValueAsString(row.getCell(columnMap.get("客户编码")));
                    stockName = getCellValueAsString(row.getCell(columnMap.get("存货名称")));
                    warehouse = getCellValueAsString(row.getCell(columnMap.get("仓库")));

                    // 读取业务员2字段，如果存在的话
                    if (columnMap.containsKey("业务员2")) {
                        salesperson2 = getCellValueAsString(row.getCell(columnMap.get("业务员2")));
                    }

                    // 处理额外字段，这些字段出现在新表格中但不影响核心计算逻辑
                    // 记录这些字段用于日志输出，但不影响核心业务逻辑
                    if (columnMap.containsKey("出库日期")) {
                        String exportDate = getCellValueAsString(row.getCell(columnMap.get("出库日期")));
                        logger.debug("行 " + (i+1) + " 出库日期: " + exportDate);
                    }

                    if (columnMap.containsKey("全月基本工资")) {
                        double baseSalary = 0;
                        Cell baseSalaryCell = row.getCell(columnMap.get("全月基本工资"));
                        if (baseSalaryCell != null) {
                            baseSalary = getCellValueAsDouble(baseSalaryCell);
                        }
                        logger.debug("行 " + (i+1) + " 全月基本工资: " + baseSalary);
                    }

                    if (columnMap.containsKey("利润")) {
                        double profit = 0;
                        Cell profitCell = row.getCell(columnMap.get("利润"));
                        if (profitCell != null) {
                            profit = getCellValueAsDouble(profitCell);
                        }
                        logger.debug("行 " + (i+1) + " 利润: " + profit);
                    }

                    // 创建工资记录对象并添加到列表
                    SalesRecord record = new SalesRecord(salesperson, quantity, paperProfit,
                            customerCode, stockName, warehouse, salesperson2);
                    records.add(record);

                } catch (Exception e) {
                    logger.error("读取第" + (i+1) + "行数据时出错: " + e.getMessage(), e);
                }
            }

            // 设置销售总量到SalaryInfo对象中
            salesInfo.setTotalSalesQuantity(totalSalesQuantity);
            logger.info("读取完成，总销售量（不含东莞诚昌）: " + totalSalesQuantity + "吨");

            // 保存salaryInfo对象，供后续使用
            GlobalDataStore.setSalaryInfo(salesInfo);

        } catch (IOException e) {
            logger.error("读取Excel文件失败: " + e.getMessage(), e);
        }

        return records;
    }
}
